<?php

namespace app\modules\search\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\clinical\models\Patient;

class SearchPatient extends Patient
{
    public function rules()
    {
        // 只有在 rules() 函数中声明的字段才可以搜索
        return [
            [['pt_id', 'dna_id', 'pt_name', 'pt_addr', 'crt_name', 'pt_intro'], 'string', 'max' => 20],
            [['rel_phone1', 'rel_phone2'], 'string', 'max' => 11],
            [['pt_hsp'], 'string', 'max' => 30],
            [['pt_birth', 'crt_date'], 'safe'],
            [['pt_sex'], 'integer']
        ];
    }

    // public function scenarios()
    // {
    //     // 旁路在父类中实现的 scenarios() 函数
    //     return Model::scenarios();
    // }

    public function search($params)
    {
        $query = Patient::find()->where(['delete_at' => 0]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'crt_date' => SORT_DESC,            
                ]
            ],
//            'pagination' => [
//                'route' => '/search/patient/?',
//            ]
        ]);

        // 从参数的数据中加载过滤条件，并验证
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $this->clearDate(['pt_birth', 'crt_date']);

        // 增加过滤条件来调整查询对象
        $query->andFilterWhere(['=', 'pt_id', $this->pt_id])
              ->andFilterWhere(['=', 'dna_id', $this->dna_id])
              ->andFilterWhere(['like', 'pt_name', $this->pt_name])
              ->andFilterWhere(['=', 'pt_sex', $this->pt_sex])
              ->andFilterWhere(['like', 'pt_birth', $this->pt_birth])
              ->andFilterWhere(['like', 'pt_addr', $this->pt_addr])
              ->andFilterWhere(['like', 'rel_phone1', $this->rel_phone1])
              ->andFilterWhere(['like', 'rel_phone2', $this->rel_phone2])
              ->andFilterWhere(['like', 'pt_hsp', $this->pt_hsp])
              ->andFilterWhere(['like', 'pt_intro', $this->pt_intro])
              ->andFilterWhere(['=', 'crt_name', $this->crt_name])
              ->andFilterWhere(['like', 'crt_date', $this->crt_date]);

        return $dataProvider;
    }

    protected function clearDate($arr)
    {
        foreach ($arr as $param) {
            $this->$param = preg_replace('/_*(-|:)_*(-|:)_*/', '', $this->$param);
        }
    }
}